﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;

namespace _NET5中的鉴权授权正确方式.Controllers
{
    public class AccountController : Controller
    {
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Login(IFormCollection formData)
        {
            string userName = formData["userName"].ToString();
            string passWord = formData["password"].ToString();

            if (userName == "test" && passWord == "123456")
            {
                // 模拟从数据库中获取了用户的角色列表
                var roleList = new List<string>()
                {
                    "Admin",
                    "Test",
                    "User"
                };

                // 用Claim保存用户信息
                List<Claim> claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name,"测试账号"),
                    new Claim("id","1"),
                    new Claim("account",userName)
                    // 可以继续增加
                };

                // 再增加角色
                foreach (var role in roleList)
                {
                    claims.Add(new Claim(ClaimTypes.Role, role));
                }

                //把用户信息装到ClaimsPrincipal
                ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));

                //登录，把用户信息写入到cookie
                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal,
                    new AuthenticationProperties
                    {
                        ExpiresUtc = DateTime.Now.AddMinutes(30)
                    }).Wait();

                //跳转到首页
                return RedirectToAction("Index", "Home");
            }
            else
            {
                TempData["err"] = "账号或密码不正确";
                //账号密码不对,跳回登录页
                return RedirectToAction("Login", "Account");
            }
        }

        public IActionResult AccessDenied()
        {
            return View();
        }

        public IActionResult Logout()
        {
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Login", "Account");
        }
    }
}
